package com.gx.common.utils;

import cn.hutool.http.useragent.Browser;
import cn.hutool.http.useragent.OS;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;

import javax.servlet.http.HttpServletRequest;

public class IpUtil {
    /**
     * 获取发起请求的IP地址
     */

    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");

        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");

        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();

        }
        return ip;

    }

    /**
     * 获取发起请求的浏览器名称
     */

    public static String getBrowserName(HttpServletRequest request) {
        String ua = request.getHeader("User-Agent");
        UserAgent userAgent = UserAgentUtil.parse(ua);
        Browser browser = userAgent.getBrowser();
        OS os = userAgent.getOs();
        return os.getName() + ": " + browser.getName();
    }

}